<template>
  <t-modal
    :title="filterTitleName"
    width="950px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="handleOk()"
    wrapClassName="addTableModal-container"
    v-bind="footer"
    forceRender
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item label="排序号" prop="sort">
          <a-input v-model="form.sort" placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-form-model-item label="编号" prop="fileCode">
          <a-input
            v-model="form.fileCode"
            placeholder="请输入"
            :disabled="checkSoucre.fileCode ? true : false"
          ></a-input>
          <span class="suffix" @click="handleQuote()">
            检索
          </span>
        </a-form-model-item>
        <a-form-model-item label="名称" prop="fileName">
          <a-input
            v-model="form.fileName"
            placeholder="请输入"
            :disabled="checkSoucre.fileName ? true : false"
          >
          </a-input>
          <span class="suffix" @click="handleQuote()">
            检索
          </span>
        </a-form-model-item>
        <a-form-model-item label="类别" prop="fileType">
          <a-select
            v-model="form.fileType"
            placeholder="请选择"
            showSearch
            allowClear
            :filter-option="filterOption"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in typeSource"
              :key="item.dicItemCode"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="文件"
          prop="fileList"
          :rules="{
            required: true,
            message: '请选择文件',
          }"
        >
          <bjUploadFile
            :viewMode="checkSoucre.dfsFileUuid ? true : false"
            type="file"
            :count="1"
            v-model="form.fileList"
            @download="downloadFile($event)"
            @change="upLoadFile($event)"
            @preview="viewFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 检索引用 -->
    <retrievalQuoteModal
      :visible.sync="retrievalQuoteModal.visible"
      :fileCode="retrievalQuoteModal.fileCode"
      :fileName="retrievalQuoteModal.fileName"
      @retrievalChange="retrievalChange"
    ></retrievalQuoteModal>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/TopVUI";
import { downloadDfs } from "@/utils/TopVUI";
//附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
//检索引用
import retrievalQuoteModal from "@/pages/customPage/projectArchiveConfig/components/retrievalQuoteModal.vue";
import { addTableMaterial, updateTableMaterial } from "@/api/knowledgeBase";
import { getDicItemByCode } from "@/api/common.js";
export default {
  components: {
    bjUploadFile,
    retrievalQuoteModal,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    footer: {
      type: Object,
      default() {
        return {};
      },
    },
    operateType: {
      type: [Number, String],
      default: 1,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      form: {
        //排序号
        sort: "",
        //编号
        fileCode: "",
        //名称
        fileName: "",
        //类别
        fileType: undefined,
        //文件
        fileList: [],
      },
      rules: {
        sort: [
          {
            required: true,
            message: "请输入排序号",
          },
        ],
        fileCode: [
          {
            required: true,
            message: "请输入编号",
          },
        ],
        fileName: [
          {
            required: true,
            message: "请输入名称",
          },
        ],
        fileType: [
          {
            required: true,
            message: "请选择类别",
          },
        ],
      },
      //类别
      typeSource: [],
      //检索引用
      retrievalQuoteModal: {
        visible: false,
        //编号
        fileCode: "",
        //名称
        fileName: "",
      },
      checkSoucre: {},
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    filterTitleName() {
      let { operateType } = this;
      switch (Number(operateType)) {
        case 1:
          return "新增";

        case 2:
          return "编辑";

        default:
          return "新增";
      }
    },
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getTypeSelectData();
          let { uuid } = this.parameter;
          if (uuid) {
            this.getDetail();
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    addTableMaterial,
    updateTableMaterial,
    //检索引用
    handleQuote() {
      let { fileCode, fileName } = this.form;
      this.retrievalQuoteModal.fileCode = fileCode;
      this.retrievalQuoteModal.fileName = fileName;
      this.retrievalQuoteModal.visible = true;
    },
    //选择的文件
    retrievalChange(data) {
      let { fileCode, fileName, dfsFileUuid, url } = data;
      this.checkSoucre = data;
      this.form.fileCode = fileCode;
      this.form.fileName = fileName;
      if (fileName) {
        let lastIdx = fileName.lastIndexOf(".");
        let fileType = "." + fileName.substring(lastIdx + 1);
        this.form.fileList = [
          {
            fileName: fileName,
            fileType,
            dfsFileUuid: dfsFileUuid,
            url: url,
          },
        ];
      }
    },

    //上传附件
    upLoadFile({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["fileList"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          const length = this.form.fileList.length - 1;
          this.$set(this.form.fileList[length], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form.fileList[length], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form["fileList"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["fileList"][index], "loading", false);
        });
    },
    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let { url } = row;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    getDetail() {
      let { parameter } = this;
      this.form = {
        //排序号
        sort: parameter.sort,
        //编号
        fileCode: parameter.fileCode,
        //名称
        fileName: parameter.fileName,
        //类别
        fileType: parameter.fileType,
        //文件
        fileList: parameter?.files ? JSON.parse(parameter?.files ?? "[]") : [],
      };
    },

    //查询类别下拉框
    getTypeSelectData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "projectInformationType" })
          .then((res) => {
            let { data } = res;
            this.typeSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.typeSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    handleOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { directoryUuid, tenantCode, uuid } = this.parameter;
          let { form } = this;
          //附件
          const files = form.fileList.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          const ids = form.fileList.map((v) => v.dfsFileUuid);
          let formJson = {
            directoryUuid,
            tenantCode,
            //排序号
            sort: form.sort,
            //编号
            fileCode: form.fileCode,
            //名称
            fileName: form.fileName,
            //类别
            fileType: form.fileType,
            //文件
            files: JSON.stringify(files),
            dfsFileUuid: ids.toString(),
          };
          let pathUrl = "";
          //编辑
          if (uuid) {
            formJson.uuid = uuid;
            pathUrl = "updateTableMaterial";
          }
          //新增
          else {
            pathUrl = "addTableMaterial";
          }
          this[pathUrl](formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.$parent.getTableData();
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch();
        }
      });
    },
    //重置表单
    resetForm() {
      this.checkSoucre = {};
      this.form = {
        //排序号
        sort: "",
        //编号
        fileCode: "",
        //名称
        fileName: "",
        //类别
        fileType: undefined,
        //文件
        fileList: [],
      };
      this.$refs.ruleForm.resetFields();
    },
    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.addTableModal-container {
  .curve-modal-body {
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 100px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
      .quote {
        padding-right: 46px;
      }
      .suffix {
        cursor: pointer;
        position: absolute;
        right: 6px;
        top: -11px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: #1677ff;
        letter-spacing: 1px;
      }
      .bj-upload-file {
        .choosed-file-warp {
          width: 100%;
        }
      }
    }
  }
}
</style>
